<?php

namespace App\Http\Middleware;

use Auth;
use Closure;
use Event;
use Overtrue\LaravelWeChat\Events\WeChatUserAuthorized;

class WechatOauthWithMultiCallback
{
    public function handle($request, Closure $next, $account = 'default')
    {
        $isNewSession = false;
        $sessionKey = \sprintf('wechat.oauth_user.%s', $account);
        $officialAccount = app(\sprintf('wechat.official_account.%s', $account));

        $session = session($sessionKey, []);

        if (!$session) {
            if ($request->has('code')) {
                session([$sessionKey => $officialAccount->oauth->user() ?? []]);
                $isNewSession = true;

                Event::fire(new WeChatUserAuthorized(session($sessionKey), $isNewSession, $account));

                return redirect()->to($this->getTargetUrl($request));
            }

            session()->forget($sessionKey);

            return redirect(wechat_oauth_url($request->fullUrl()));
        }

        Event::fire(new WeChatUserAuthorized(session($sessionKey), $isNewSession, $account));

        return $next($request);
    }

    protected function getTargetUrl($request)
    {
        $queries = array_except($request->query(), ['code', 'state']);

        return $request->url().(empty($queries) ? '' : '?'.http_build_query($queries));
    }
}
